package com.sdkj.fixed.asset.common.utils;

import com.sdkj.fixed.asset.common.exception.FileOutOfMaxSizeException;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;


public class FileUtils {
    public static File uploadFile(MultipartFile file) throws IllegalStateException, IOException {
        // 验证大小
        String maxLength = "10485760";
        if (file.getSize() > Integer.valueOf(maxLength)) {
            throw new FileOutOfMaxSizeException("文件不能超过" + Integer.valueOf(maxLength) / 1024 + "kb");
        }
        String fileName = genetateFileName(file.getOriginalFilename());
        String filePath = generateDir();
        File newfile = new File(filePath, fileName);
        file.transferTo(newfile);
        return newfile;
    }

    public static String generateDir() {
        //保存文件地址
        // get current dir
        String dirPath = File.separator + TimeTool.getTimeDate12().substring(0, 4) + File.separator
                + TimeTool.getTimeDate12().substring(4, 6) + File.separator + TimeTool.getTimeDate12().substring(6, 8)
                + File.separator + TimeTool.getTimeDate12().substring(8, 10) + File.separator;
        dirPath = dirPath.replaceAll("\\\\", "/");
        if (!new File(dirPath).exists()) {
            new File(dirPath).mkdirs();
        }
        return dirPath;
    }

    private static String genetateFileName(String originName) {
        String fileName = UUID.randomUUID().toString().replace("-", "");
        String suffix = originName.substring(originName.lastIndexOf(".") + 1, originName.length()).toLowerCase();
        String newFileName = fileName + "." + suffix;
        return newFileName;
    }

    //获取文件后缀名
    public static String getExtensionFileName(String originName) {
        String suffix = originName.substring(originName.lastIndexOf(".") + 1, originName.length()).toLowerCase();
        return suffix;
    }
}
